import {UnwrapNestedRefs} from "@vue/reactivity";


interface OptionsByApi {
    api: PromiseFun
    params?: Record<string, any>
}


/**
 * 批量调用接口
 *
 */
class BeachRequestManager {

    /**
     * 批量请求管理器返回响应数据 不是  promise
     */
    useBeachRequest(options: Record<string, OptionsByApi>): UnwrapNestedRefs<any> {

        // 定义响应后数据
        const optionsData: any = reactive({})

        const apiKey: string[] = Object.keys(options)

        // 获取接口集合 定义返回数据类型
        let apis: Promise<any>[] = apiKey.map((k) => {
            const value: OptionsByApi = options[k]

            // 定义健值
            optionsData[k] = []

            return value.api(toRaw(value.params) || {});
        })


        async function callAllApi() {
            const res: PromiseSettledResult<any>[] = await Promise.allSettled<Promise<any>>(apis);

            res.forEach((item, index) => {
                const key = apiKey[index]
                if (item.status == 'fulfilled') {
                    optionsData[key] = item.value
                }


                if (item.status == 'rejected') {
                    console.log("接口异常", item);
                }
            })

        }

        callAllApi().then(() => {})

        return optionsData

    }

}

let beachRequestManager = new BeachRequestManager();
export default beachRequestManager

